package com.oneonefive.educationsystem.filter;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSON;
import com.oneonefive.educationsystem.domain.Login;
import io.netty.util.internal.StringUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("userId");
        if (StringUtil.isNullOrEmpty(token)) {
            filterChain.doFilter(request, response);
            log.info("未找到token");
            return;
        }
        String userid;
        try {
            JWT jwt = JWTUtil.parseToken(token);
            userid = jwt.getPayload("userid").toString();
        } catch (Exception e) {
            e.printStackTrace();
            log.info("token错误");
            throw new RuntimeException("token错误");
        }
        String s = stringRedisTemplate.opsForValue().get("login:" + userid);
        Login user = JSON.parseObject(s, Login.class);
        System.out.println(user);
        if (Objects.isNull(user)) {
            log.info("用户未登录");
            throw new RuntimeException("用户未登录");
        }
        //存入securityContextHolder
        UsernamePasswordAuthenticationToken token1 =
                new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(token1);
        //放行
        filterChain.doFilter(request, response);
    }

}
